//
//  BasePopUpView.swift
//  MT
//
//  Created by M on 2019/12/16.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory

@objc
protocol AlertDelegate: NSObjectProtocol {
    
    /// 点击右上按钮回调
    @objc optional func alertViewDidClickDismissButton(_ view: BaseAlertView)
    
    /// 触发背景遮罩手势回调
    @objc optional func alertViewDidClickBackgroundCover(_ view: BaseAlertView)
    
    /// 弹窗已关闭
    @objc optional func alertViewDidDismissed(_ view: BaseAlertView)
    
}

class BaseAlertView: UIView {
    
    /// 代理
    weak var delegate: AlertDelegate?
    
    /// 点击右上按钮回调
    var dismissCallBack: ((_ view: BaseAlertView) -> (Swift.Void))?
    
    /// 弹出方式
    @objc
    enum AlertStyle: Int {
        case center
        case bottom
    }
    var popStyle: AlertStyle {
        didSet {
            self.layer.cornerRadius = popStyle == .bottom ? 0 : 8
        }
    }
    
    /// 关闭样式
    @objc
    enum DismissStyle: Int {
        case text
        case icon
    }
    var dismissStyle: DismissStyle = .icon {
        didSet {
            if dismissStyle == .icon {
                dismissButton.setTitle("", for: .normal)
                dismissButton.setImage(UIImage(named: "icon_dismiss"), for: .normal)
                dismissButton.snp.updateConstraints { (make) in
                    make.width.equalTo(20)
                }
            } else if dismissStyle == .text {
                dismissButton.setImage(nil, for: .normal)
            }
        }
    }
    
    /// 最大宽度 - 仅在 PopStyle 为 center 时生效
    var screenWidthRatio: CGFloat = 0.7
    /// popView宽度
    private var popViewWidth: CGFloat {
        return screenWidthRatio * ScreenWidth
    }
    /// 是否自动消失 - 仅在 PopStyle 为 center 时生效 - 默认值为不自动消失
    var shouldAutoDismiss: Bool = false
    /// 点击遮罩背景是否触发动画消失 - 默认为 true
    var isDismissAnimated: Bool = true
    /// 展示时长 - 只有 isDismissAnimated 为 true 时有效
    var displayDuration: TimeInterval = 3.0
    
    /// 动画时长
    var duration: TimeInterval = 0.25
    
    /// 是否需要背景遮罩 - 默认为 true
    var isBackgroundCoverEnabled: Bool = true
    /// 背景遮罩颜色 - 只有在 isBackgroundCoverEnabled 同时为 true 时生效
    var backgroundCoverBackgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8)
    /// 背景遮罩关闭手势是否开启
    var isBackgroundCoverViewGestureEnabled: Bool = true
    /// 背景遮罩触发手势后是否自动关闭 - 只有在 isBackgroundCoverEnabled 和 isBackgroundCoverViewGestureEnabled 和 isBackgroundCoverViewGestureEnabled 同时为 true 时生效
    var shouldBackgroundCoverViewGestureAutoDismiss: Bool = true
    
    /// 背景遮罩视图
    internal var backgroundCoverView: UIView?
    
    /// 标题 View
    lazy var titleView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 52, height: 22))
        view.backgroundColor = UIColor.theme.main
        view.clipRectCorner(direction: [.topRight, .bottomRight], cornerRadius: 11)
        return view
    }()
    
    /// 标题
    var title: String?
    /// 标题 Label
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCRegularFont(14)
        label.textColor = .white
        return label
    }()
    
    /// 是否隐藏关闭按钮
    public var isDismissButtonHidden: Bool = false {
        didSet {
            dismissButton.isHidden = isDismissButtonHidden
        }
    }
    /// 关闭按钮
    lazy var dismissButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "icon_dismiss"), for: .normal)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(alertView(didClickDismissButton:)), for: .touchUpInside)
        return btn
    }()

    init(height: CGFloat = 200, popStyle: AlertStyle = .bottom) {
        self.popStyle = popStyle
        super.init(frame: CGRect(x: 0, y: ScreenHeight, width: ScreenWidth, height: height + (popStyle == .bottom ? ScreenBottomExtraOffset : 0)))
        basePopUpViewInitializeUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 视图弹窗消失
    public func dismiss(animated: Bool = true, completion: ((_: Bool) -> Swift.Void)? = nil) {
        removeBackgroundCoverView()
        !animated ? removeFromSuperview() : UIView.animate(withDuration: duration, animations: {
            if self.popStyle == .bottom {
                self.frame = CGRect(x: self.mt_x, y: ScreenHeight, width: self.mt_width, height: self.mt_height)
            }
            self.alpha = 0
        }, completion: { (flag) in
            completion?(flag)
            if let delegate = self.delegate {
                delegate.alertViewDidDismissed?(self)
            }
            self.removeFromSuperview()
        })
    }
    
}

// MARK: ------------------ UI 初始化 ----------------------
extension BaseAlertView {
    
    private func basePopUpViewInitializeUI() {
        backgroundColor = UIColor.common.x161616
        alpha = 0
        addSubview(titleView)
        addSubview(titleLabel)
        addSubview(dismissButton)
        
        titleView.snp.makeConstraints { (make) in
            make.left.equalTo(self)
            make.top.equalTo(self).offset(16)
            make.width.equalTo(52)
            make.height.equalTo(22)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.right.equalTo(titleView).offset(-6)
            make.top.equalTo(titleView)
            make.width.equalTo(30)
            make.height.equalTo(titleView)
        }
        
        dismissButton.snp.makeConstraints { (make) in
            make.top.equalTo(self).offset(16)
            make.right.equalTo(self).offset(-20)
            make.width.height.equalTo(20)
        }
    }
    
}

// MARK: ------------------ 样式 添加 / 修改 ----------------------
extension BaseAlertView {
    
    /// 设置字体
    public func set(text: String?, color: UIColor? = UIColor.text.x1d1a1a, font: UIFont? = PingFangSCRegularFont(14)) {
        dismissStyle = .text
        self.dismissButton.setTitle(text, for: .normal)
        self.dismissButton.setTitleColor(color, for: .normal)
        self.dismissButton.titleLabel?.font = font
        if let width = text?.width(font: font ?? PingFangSCRegularFont(14), maxHeight: CGFloat.greatestFiniteMagnitude) {
            dismissButton.snp.updateConstraints { (make) in
                make.width.equalTo(width + 10)
            }
        }
    }
    
    /// 设置关闭样式图标
    public func set(dismissImage: UIImage) {
        dismissStyle = .icon
        self.dismissButton.setImage(dismissImage, for: .normal)
        self.set(text: nil, color: nil, font: nil)
    }
    
    /// 设置背景遮罩视图
    public func setBackgroundCoverView() {
        if !isBackgroundCoverEnabled { return }
        let cover = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight))
        cover.backgroundColor = backgroundCoverBackgroundColor
        cover.alpha = 0
        self.backgroundCoverView = cover
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(alertView(didActiveBackgroundCoverViewGestureRecognizer:)))
        cover.addGestureRecognizer(tap)
        
        UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(cover)
    }
    
    /// 移除背景遮罩视图
    public func removeBackgroundCoverView() {
        UIView.animate(withDuration: isDismissAnimated ? duration : 0, animations: {
            self.backgroundCoverView?.alpha = 0
        }) { (_) in
            self.backgroundCoverView?.removeFromSuperview()
            self.backgroundCoverView = nil
        }
    }
    
}

// MARK: ------------------ 动画 ----------------------
extension BaseAlertView {
    
    /// 展示弹窗
    @objc public func present(animated: Bool = true, completion: ((_: Bool) -> Swift.Void)? = nil) {
        titleView.isHidden = title == nil
        titleLabel.isHidden = title == nil
        titleLabel.text = title
        
        setBackgroundCoverView()
        //UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(self)
        if let p = UIApplication.mt_keyWindow?.rootViewController?.presentedViewController {
            p.view.addSubview(self)
        } else {
            UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(self)
        }
        if popStyle == .center {
            let width = ScreenWidth * screenWidthRatio
            self.frame = CGRect(x: (ScreenWidth - width) / 2, y: (ScreenHeight - self.mt_height) / 2, width: width, height: self.mt_height)
        }
        UIView.animate(withDuration: animated ? duration : 0, animations: {
            if self.popStyle == .bottom {
                self.frame = CGRect(x: self.mt_x, y: ScreenHeight - self.mt_height, width: self.mt_width, height: self.mt_height)
            }
            self.alpha = 1
            self.backgroundCoverView?.alpha = 1
            
        }) { (flag) in
            if self.shouldAutoDismiss && self.popStyle == .center {
                DispatchQueue.main.asyncAfter(deadline: .now() + self.displayDuration) {                
                    self.dismiss(animated: self.isDismissAnimated, completion: nil)
                }
            }
            if let completion = completion {
                completion(flag)
            }
        }
    }
    
    
    
}

// MARK: ------------------ 事件方法 ----------------------
@objc
extension BaseAlertView {
    
    /// 点击右上角按钮
    public func alertView(didClickDismissButton sender: UIButton) {
        dismiss(animated: isDismissAnimated, completion: nil)
        if let delegate = delegate {
            delegate.alertViewDidClickDismissButton?(self)
        }
        if let callBack = dismissCallBack {
            callBack(self)
        }
    }
    
    /// 触发背景遮罩点击手势
    private func alertView(didActiveBackgroundCoverViewGestureRecognizer gestureRecognizer: UITapGestureRecognizer) {
        if !isBackgroundCoverViewGestureEnabled { return }
        if let delegate = delegate {
            delegate.alertViewDidClickBackgroundCover?(self)
        }
        if shouldBackgroundCoverViewGestureAutoDismiss {
            dismiss(animated: isDismissAnimated, completion: nil)
        }
    }
    
}
